<template>
  <div class="week-body">
    <div style="width: 700px; padding: 20px 0; margin: auto;">
      <el-card class="card">{{date}}</el-card>
      <el-card class="card">
        年：
        <el-select v-model="year">
          <el-option
            v-for="(item, index) in yearList"
            :key="index"
            :label="item.value"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" @click="yearClick">搜索</el-button>
      </el-card>
      <el-card class="card">
        月：
        <el-select v-model="firstMonth">
          <el-option
            v-for="(item, index) in monthList"
            :key="index"
            :label="item.value"
            :value="item.value"
          />
        </el-select>
        --
        <el-select v-model="secondMonth">
          <el-option
            v-for="(item, index) in monthList"
            :key="index"
            :label="item.value"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" @click="monthClick">搜索</el-button>
      </el-card>
      <el-card class="card">
        周：
        <el-select v-model="firstWeek">
          <el-option
            v-for="(item, index) in weekList"
            :key="index"
            :label="item.value"
            :value="item.value"
          />
        </el-select>
        --
        <el-select v-model="secondWeek">
          <el-option
            v-for="(item, index) in weekList"
            :key="index"
            :label="item.value"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" @click="weekClick">搜索</el-button>
      </el-card>
    </div>
  </div>
</template>
<script>
var TIMESTAMP = 24 * 60 * 60 * 1000

export default {
  data: () => ({
    date: Date(),
    yearList: [],
    monthList: [],
    weekList: [],
    year: '',
    firstMonth: '',
    secondMonth: '',
    firstWeek: '',
    secondWeek: '',
  }),
  methods: {
    yearClick() {
      var startTime = ''
      var endTime = ''
      if (this.year) {
        startTime = this.year + '-01-01 00:00:00'
        endTime = this.year + '-12-31 23:59:59'
      }
      console.log(startTime, endTime)
    },
    monthClick() {
      var startTime = ''
      var endTime = ''
      if (this.firstMonth && this.secondMonth) {
        if (this.firstMonth > this.secondMonth) {
          var temp = this.firstMonth
          this.firstMonth = this.secondMonth
          this.secondMonth = temp
        }
        var firstArray = this.firstMonth.split('-')
        var secondArray = this.secondMonth.split('-')
        var secondLsatDay = getMonthDays(secondArray[0], secondArray[1])
        startTime = new Date(firstArray[0], firstArray[1] - 1, 1).format('yyyy-MM-dd') + ' 00:00:00'
        endTime = new Date(secondArray[0], secondArray[1] - 1, secondLsatDay).format('yyyy-MM-dd') + ' 23:59:59'
        console.log(startTime, endTime)
      }
    },
    weekClick() {
      var startTime = ''
      var endTime = ''
      var firstWeekStart = ''
      var firstWeekEnd = ''
      var secondWeekStart = ''
      var secondWeekEnd = ''
      if (this.firstWeek && this.secondWeek) {
        if (this.firstWeek > this.secondWeek) {
          var temp = this.firstWeek
          this.firstWeek = this.secondWeek
          this.secondWeek = temp
        }
        var firstArray = this.firstWeek.split('W')
        var secondArray = this.secondWeek.split('W')

        function setWeek (array) {
          var start = ''
          var end = ''
          var year = parseInt(array[0])
          var week = parseInt(array[1])
          var time = new Date(year, 0, 1)
          var day = time.getDay()
          var cut = cutDays(day)
          var count = getYearDays(year)
          start = new Date(time.getTime() + ((week - 1) * 7 + cut ) * TIMESTAMP).format('yyyy-MM-dd') + ' 00:00:00'
          end = new Date(time.getTime() + (week * 7 - 1  + cut ) * TIMESTAMP).format('yyyy-MM-dd') + ' 23:59:59'
          return {
            start: start,
            end: end,
          }
        }
        // firstWeek
        var firstWeek = setWeek(firstArray)
        firstWeekStart = firstWeek.start
        firstWeekEnd = firstWeek.end
        // secondWeek
        var secondWeek = setWeek(secondArray)
        secondWeekStart = secondWeek.start
        secondWeekEnd = secondWeek.end

        startTime = firstWeekStart
        endTime = secondWeekEnd
        console.log(firstWeekStart, secondWeekEnd)
      }
    },
    initYear() {
      var now = new Date()
      var startYear = 2017
      var curYear = now.getFullYear()
      this.yearList = []
      for (var i = 0; i <= (curYear - startYear); i++) {
        this.yearList.push({
          value: startYear + i,
        })
      }
    },
    initMonth() {
      var now = new Date()
      var startYear = 2017
      var curYear = now.getFullYear()
      var curMonth = now.getMonth() + 1
      this.monthList = []
      // 今年之前
      for (var i = 0; i < (curYear - startYear); i++) {
        for (var j = 1; j <= 12; j++) {
          this.monthList.push({
            value: (startYear + i) + '-' + j
          })
        }
      }
      // 今年
      for (var i = 1; i <= curMonth; i++) {
        this.monthList.push({
          value: curYear + '-' + i
        })
      }
    },
    initWeek() {
      var now = new Date()
      var temp = new Date()
      temp.setMonth(0)
      temp.setDate(1)
      var difference = (now - temp) / TIMESTAMP;
      var startYear = 2017
      var curYear = now.getFullYear()
      var curMonth = now.getMonth() + 1
      var curDate = now.getDate()
      this.weekList = []
      // 今年之前
      for (var i = 0; i < (curYear - startYear); i++) {
        var year = startYear + i
        var time = new Date(year, 0, 1)
        var day = time.getDay()
        var cut = cutDays(day)
        var count = getYearDays(year) - cut
        var weekLen = Math.ceil(count / 7)
        for (var j = 1; j <= weekLen; j++) {
          this.weekList.push({
            value: year + 'W' + j
          })
        }
      }
      // 今年
      var count = getYearDays(curYear)
      var weekLen = Math.ceil(difference / 7)
      for (var j = 1; j <= weekLen; j++) {
        this.weekList.push({
          value: curYear + 'W' + j
        })
      }
    }

  },
  mounted() {
    this.initYear()
    this.initMonth()
    this.initWeek()
  }
  /*
  mounted() {
    function getDaysByYear(year) {
      if( ( (year % 4 === 0) && (year % 100 !== 0) ) || ( year % 400 === 0 ) ) {
        return 366;
      }
      return 365;
    }

    var TIMESTAMP = 24 * 60 * 60 * 1000
    // var str = '2017-01-01'
    var str = ''
    var day1 = new Date(str)
    var day2 = new Date(str)
    day2.setMonth(0)
    day2.setDate(1)
    var cut = 0
    var firstDay = day2.getDay()
    switch (firstDay) {
      case 2:
        cut = 6;
        break;
      case 3:
        cut = 5;
        break;
      case 4:
        cut = 4;
        break;
      case 5:
        cut = 3;
        break;
      case 6:
        cut = 2;
        break;
      case 0:
        cut = 1;
      default:
        cut = cut;
    }

    var timestamp = day1 - day2
    var numberOfDay = Math.ceil(timestamp / TIMESTAMP) - cut + 1
    var currentWeek = Math.ceil(numberOfDay / 7)
    console.log(numberOfDay, currentWeek)
  }
  */
}

Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1,
        (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

/**
 * 判断是否为整数
 * @param obj
 * @return {boolean}
 */
function isInteger(obj) {
    return Math.floor(obj) === obj
}

/**
 * 判断是否为数字
 * @param num
 * @return {boolean}
 */
function isNumber(num) {
    var number = +num;

    if ((number - number) !== 0) {
        // Discard Infinity and NaN
        return false;
    }

    if (number === num) {
        return true;
    }

    if (typeof num === 'string') {
        // String parsed, both a non-empty whitespace string and an empty string
        // will have been coerced to 0. If 0 trim the string and see if its empty.
        if (number === 0 && num.trim() === '') {
            return false;
        }
        return true;
    }
    return false;
}

/**
 * 保留两位小数
 * @param num
 * @param isRate 是否为率
 * @return {*}
 */
function parseNum(num, isRate) {
    if (isNumber(num)) {
        if (isInteger(num)) {
            if (isRate) {
                return (parseFloat(num) * 100).toFixed(2) + '%';
            } else {
                return num;
            }
        } else {
            if (isRate) {
                return (parseFloat(num) * 100).toFixed(2) + '%';
            } else {
                return parseFloat(num).toFixed(2);
            }
        }
    } else {
        return num;
    }
}

// 获取当年天数
function getYearDays(year) {
  if( ( (year % 4 === 0) && (year % 100 !== 0) ) || ( year % 400 === 0 ) ) {
    return 366;
  }
  return 365;
}

// 获取当前月份的天数
function getMonthDays(year, month) {
  var days = new Date(year, month, 0)
  return days.getDate()
}

function cutDays(day) {
  var cut = 0
  switch (day) {
    case 2:
      cut = 6;
      break;
    case 3:
      cut = 5;
      break;
    case 4:
      cut = 4;
      break;
    case 5:
      cut = 3;
      break;
    case 6:
      cut = 2;
      break;
    case 0:
      cut = 1;
      break;
    default:
      cut = cut;
  }
  return cut
}

function weekNumOfYear2Date(weekOfYear) {
    weekOfYear = weekOfYear.toUpperCase();
    if (weekOfYear.indexOf("W") < 0) {
        return weekOfYear;
    }
    var fstDayYear = new Date(weekOfYear.split('W')[0], 0, 1, 0, 0, 0);
    var weekNum = weekOfYear.split('W')[1];
    var fstDayWeek = fstDayYear.getDay();
    var offset;
    if (fstDayWeek) {
        offset = fstDayWeek === 1 ? 0 : 7 - fstDayWeek + 1;
    } else {
        offset = 1;
    }
    var startDate = new Date(
        fstDayYear.valueOf() + 24 * 60 * 60 * 1000 * ((weekNum - 1) * 7
        + offset)).format("yyyy-MM-dd");
    var endDate = new Date(
        fstDayYear.valueOf() + 24 * 60 * 60 * 1000 * (weekNum * 7 - 1
        + offset)).format("yyyy-MM-dd");
    return startDate + ' ~ ' + endDate;
}

</script>
<style lang="scss" scoped>
.week-body {
  width: 100vw;
  height: 100vh;
  background-image: linear-gradient(to top, #a18cd1 0%, #fbc2eb 100%);
}
.card {
  margin-bottom: 20px;
}
</style>
